package Hot100;

import java.util.Stack;

public class 字符串解码 {
    public String decodeString(String s) {
        Stack<String> stack = new Stack<>();
        char[] charArray = s.toCharArray();
        StringBuilder res = new StringBuilder();
        for (int i = charArray.length - 1; i >= 0; i--) {
            if (charArray[i] == '[') {
                StringBuilder temp = new StringBuilder();
                while (!stack.peek().equals("]")) temp.append(stack.pop());
                String copy = temp.toString();
                stack.pop();
                int end = i--;
                while (i >= 0 && Character.isDigit(charArray[i])) i--;
                int num = Integer.parseInt(s.substring(++i, end));
                while (--num != 0) temp.append(copy);
                stack.push(temp.toString());
            } else stack.push(charArray[i] + "");
        }
        while (!stack.isEmpty()) res.append(stack.pop());
        return res.toString();
    }
}
